package com.lalosoft.gastostarjetaweb.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lalosoft.gastostarjetaweb.Constants;
import com.lalosoft.gastostarjetaweb.dao.EmailDao;
import com.lalosoft.gastostarjetaweb.model.Email;
import com.lalosoft.gastostarjetaweb.util.DateUtils;


@SuppressWarnings("serial")
public class EnviarEmailServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger("EnviarEmailServlet");
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String remitente = req.getParameter("to");
		String mensaje = req.getParameter("mensaje");
		String asunto = req.getParameter("asunto"); 
		
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

//        String msgBody = "Esto es un mail de prueba";

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("admin@gastostarjeta.appspotmail.com", "Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(remitente, ""));
            msg.setSubject(asunto);
            msg.setText(mensaje);
            Transport.send(msg);
            
            log.log(Level.WARNING, "Email enviado correctamente");

    		Email email = new Email();
    		email.setAsunto(asunto);
    		email.setEstado(Constants.ESTADO_ENVIADO);
    		email.setMensaje(mensaje);
    		email.setRemitente(remitente);
    		email.setFecha(DateUtils.now(Constants.NOW));
    		EmailDao.saveEmail(email);
    		
    		log.log(Level.WARNING, "Email enviado guardado correctamente");
    		
			List<Email> list = EmailDao.findByState(Constants.ESTADO_RECIBIDO);
			req.setAttribute("emails", list);
		    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/inbox.jsp");
		    requestDispatcher.forward(req, resp);
        } catch (AddressException e) {
        	log.log(Level.WARNING, "Error en direccion de enviar email: " + e.getMessage(), e);
        } catch (MessagingException e) {
        	log.log(Level.WARNING, "Error en enviar email: " + e.getMessage(), e);
        }
	}

}
